﻿/*
==============================================================================
//  用户管理 的页面控制层代码。
==============================================================================
*/
(function ($) {

    $.util.namespace("views.User.UserManage");

    var tree = "#tree", dg = "#dg", queryFm = "#queryFm";
    var currentArgument = {};
    window.views.User.UserManage.initPage = function (permissions, currentUserId) {
        currentArgument.currentUserId = currentUserId;
        var data = window.jeasyui.helper.buildToolbarUsePermissionJson(permissions, true);
        data.push({ type: "button", options: { text: "刷新", iconCls: "icon-reload", onclick: function (t) { window.views.User.reloadUser(); } } });

        var treeInit = function () {

            var options = {
                url: "/Public/OrganizationJson",
                animate: true,
                onSelect: function (node) {
                    if (node.attributes.IsCompany) {
                        $(dg).datagrid("load", { companyId: node.id, model: $(queryFm).serialize() });
                    }
                    else if (node.attributes.IsDept) {
                        $(dg).datagrid("load", { deptId: node.id, model: $(queryFm).serialize() });
                    }
                    else {
                        $(dg).datagrid("load", { model: $(queryFm).serialize() });
                    }
                },
                onBeforeLoad: function (node, param) {
                    $.easyui.loading({ locale: $(this).currentRegion(), msg: "数据加载中..." });
                },
                onLoadSuccess: function (node) {
                    $.easyui.loaded($(this).currentRegion());
                    if (node == null) {
                        $(this).tree("expandAll");
                    }
                }
            };

            $(tree).tree(options);
        };

        var bindQueryButtonEvent = function () {
            $("#aquery", queryFm).click(function () {
                var queryParam = { model: $(queryFm).serialize() };
                var selected = $(tree).tree("getSelected");
                if (selected) {
                    if (selected.attributes.IsDept) { queryParam.deptId = selected.id; }
                };
                $(dg).datagrid('load', queryParam);
            });
        };

        var dataGridInit = function () {
            var toolbar = $("<div />").appendTo("body").toolbar({
                data: data
            }).toolbar("toolbar");

            var frozenColumns = function (showCheckBox) {
                var result = [];
                if (showCheckBox) {
                    result.push({ field: 'ck', checkbox: true });
                }
                var normal = [{ field: 'RealName', title: '姓名', width: 100 }, { field: 'UserName', title: '用户名', width: 100 }];
                $.util.merge(result, normal);
                return result;
            };

            var columns = function (sortableEnable) {
                var result = [];
                var normal = [
                        { field: 'LoginCode', title: '登录编号', width: 100 },
                        { field: 'RoleName', title: '所属角色', width: 100 },
                        {
                            field: 'IsDisabled', title: '是否禁用', width: 90,
                            formatter: function (value) {
                                return value ? "<b>禁用</b>" : "<b>启用</b>"
                            },
                            styler: function (val, row) {
                                if (!val)
                                { return window.comlib.stateColor.green; }
                                else
                                { return window.comlib.stateColor.red; }
                            }
                        },
                        {
                            field: 'operator', title: '操作', width: 150,
                            formatter: function (val, row, index) {
                                var strAction = "";
                                if (row.IsDisabled) {
                                    strAction = window.comlib.formatLinkButton({ "class": "btn-state" }, "icon-ok", "启用");
                                } else {
                                    strAction = window.comlib.formatLinkButton({ "class": "btn-state" }, "icon-ok", "禁用");
                                }
                                return strAction;
                            }
                        }
                ];
                if (sortableEnable) {
                    $.array.forEach(normal, function (val, index, array) {
                        $.extend(val, { sortable: true });
                    });
                }
                $.util.merge(result, normal);
                return result;
            };

            var options = {
                url: "/User/UserManageJson",
                queryParams: { first: true, rangeFilter: true },
                idField: "ID",
                toolbar: toolbar,
                rownumbers: false,
                nowrap: true,
                striped: true,
                fit: true,
                border: false,
                remoteSort: false,
                singleSelect: true,
                checkOnSelect: false,
                selectOnCheck: false,
                frozenColumns: [frozenColumns(false)],
                columns: [columns(true)],
                pagination: true,
                onBeforeLoad: function (param) {
                    return !param.first;
                },
                onLoadSuccess: function (data) {
                    $.fn.datagrid.extensions.onLoadSuccess.apply(this, arguments);//调用扩展的事件防止覆盖
                    var t = $(this), col = t.datagrid("getColumnDom", "operator"), rows = t.datagrid("getRows");
                    col.find("a.l-btn.btn-state").each(function (i, ele) {
                        $(this).click(function (e) {
                            if (rows[i].LoginCode == "cat" || rows[i].LoginCode == "rock") { $.easyui.messager.alert("此帐号为指定测试帐号，不允许禁用！"); e.stopPropagation(); }
                            else {
                                window.views.User.enableOrDisableUser(rows[i].ID, rows[i].IsDisabled);
                                e.stopPropagation();
                            }
                        });
                    });
                }
            };

            $(dg).datagrid(options);
            window.jeasyui.helper.drawTopBorderForDataGridTools($(dg));
        };

        treeInit();
        bindQueryButtonEvent();
        dataGridInit();
    };

    window.views.User.createUser = function () {
        var selectNode = $(tree).tree("getSelected");
        var param = { companyId: 0, deptId: 0 };
        if (selectNode) {
            if (selectNode.attributes.IsDept) { param.companyId = selectNode.attributes.CompanyID; param.deptId = selectNode.id; }
            else if (selectNode.attributes.IsCompany) { param.companyId = selectNode.id; }
        }

        $.easyui.showDialog({
            title: "新建用户",
            href: "/User/UserCreateForm?" + $.param(param),
            onSave: function (dialog) {
                var model = window.jeasyui.helper.formValidate(dialog);
                if (model != null) {
                    window.views.User.saveUser(model);
                } else { return false; }
            },
            width: 850,
            height: 280
        });
    };

    window.views.User.editUser = function (row) {
        row = row ? row : $(dg).datagrid("getSelected");
        if (row) {
            if (String(row.ID) == currentArgument.currentUserId) {
                $.easyui.messager.alert("不允许编辑当前登录用户的信息！");
                return;
            }
            $.easyui.showDialog({
                title: "编辑用户 " + row.RealName,
                href: "/User/UserEditForm?id=" + row.ID,
                onSave: function (dialog) {
                    var model = window.jeasyui.helper.formValidate(dialog);
                    if (model != null) {
                        window.views.User.saveUser(model);
                    } else { return false; }
                },
                width: 850,
                height: 280
            });
        }
    };

    window.views.User.saveUser = function (model) {
        $.easyui.loading({ locale: window.top.$("body"), msg: "数据处理中，请稍等..." });
        $.post("/User/SaveUser", model, function (result) {
            $.easyui.loaded(window.top.$("body"));
            window.jeasyui.helper.actionDoneCallBack.call(this, result, window.views.User.reloadUser);
        }, 'json');
    };

    window.views.User.removeUser = function (row) {
        row = row == undefined ? $(dg).datagrid("getSelected") : row;
        if (row) {
            if (String(row.ID) == currentArgument.currentUserId) {
                $.easyui.messager.alert("不允许删除当前登录用户！");
                return;
            }
            var _callback = function () {
                $.easyui.loading({ locale: $("body"), msg: "数据处理中，请稍等..." });
                $.post("/User/RemoveUser", { id: row.ID }, function (result) {
                    $.easyui.loaded($("body"));
                    window.jeasyui.helper.actionDoneCallBackWhenRemove.call(this, result, function () { $(dg).datagrid("deleteRow", $(dg).datagrid("getRowIndex", row)); });
                }, "json");
            };
            window.jeasyui.helper.confirmCallBack("确认删除 " + row.RealName + " 吗?", _callback);
        }
    };

    window.views.User.reloadUser = function () {
        $(dg).datagrid('clearSelections');
        //$(dg).datagrid('clearChecked');
        $(dg).datagrid("load");
    };


    window.views.User.resetPassWord = function (row) {
        row = row ? row : $(dg).datagrid("getSelected");
        if (row) {
            if (String(row.ID) == currentArgument.currentUserId) {
                $.easyui.messager.alert("不允许对当前登录用户重置密码！");
                return;
            }
            $.easyui.showDialog({
                title: "重置密码",
                href: "/User/ResetPassWordForm?id=" + row.ID + "&userName=" + row.UserName + "&name=" + escape(row.RealName),
                onSave: function (dialog) {
                    var model = window.jeasyui.helper.formValidate(dialog);
                    if (model != null) {
                        $.easyui.loading({ locale: window.top.$("body"), msg: "数据处理中，请稍等..." });
                        $.post("/User/ResetPassWord", model, function (result) {
                            $.easyui.loaded(window.top.$("body"));
                            window.jeasyui.helper.actionDoneCallBack.call(this, result);
                        }, "json");
                    } else { return false; }
                },
                width: 850,
                height: 190,
                topMost: true
            });
        }
    };

    window.views.User.enableOrDisableUser = function (id, state) {
        if (String(id) == currentArgument.currentUserId) {
            $.easyui.messager.alert("不允许"+ state ? "启用" : "禁用" +"当前登录用户！");
            return;
        }
        if (!$.util.isNullOrUndefined(id) && !$.util.isNullOrUndefined(state)) {
            $.easyui.loading({ locale: $("body"), msg: "数据处理中，请稍等..." });
            $.post("/User/EnableOrDisableUser", { id: id, disableState: state }, function (result) {
                $.easyui.loaded($("body"));
                window.jeasyui.helper.actionDoneCallBack.call(this, result, window.views.User.reloadUser);
            });
        }
    };

})(jQuery);